package my.jessyan.mvpart.mvp.provider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import my.jessyan.mvpart.mvp.ResourceTable;
import my.jessyan.mvpart.mvp.model.User;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;

import java.util.List;

/**
 * provider 适配器
 */

public class MainleItemProvider extends BaseItemProvider {
    private List<User> list;//数据源
    private AbilitySlice slice;

    public MainleItemProvider(List<User> list, AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    /**
     * 返回当前选中的item
     * @param i
     * @return
     */
    @Override
    public Object getItem(int i) {
        if (list != null && i >= 0 && i < list.size()){
            return list.get(i);
        }
        return null;
    }

    /**
     * 返回选中的position
     * @param i
     * @return
     */
    @Override
    public long getItemId(int i) {
        return i;
    }

    /**
     * 关联子布局
     * @param i
     * @param component
     * @param componentContainer
     * @return
     */
    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        if (component == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_item_sample, null, false);
        } else {
            cpt = component;
        }
        //查找控件对应的id 给子控件赋值
        User sampleItem = list.get(i);
        Text text = (Text) cpt.findComponentById(ResourceTable.Id_text_name);
        text.setText(sampleItem.getName());

        Image image = (Image) cpt.findComponentById(ResourceTable.Id_image_avatar);
        Glide.with(slice)
                .load(sampleItem.getAvatar_url())
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(image);

        return cpt;
    }

    public void getData(List<User> list) {
        this.list = list;
    }

}
